﻿// Copyright Microsoft

using System;
using System.Windows;
using System.Activities.Presentation.View;
using System.Activities.Presentation;
using System.Collections.Generic;
using System.Windows.Data;
using System.Globalization;
using System.Activities.Presentation.Model;
using Microsoft.VisualBasic.Activities;
using System.Windows.Controls;
using System.Windows.Input;
using System.Data.SqlClient;
using System.Collections.ObjectModel;
using Microsoft.Samples.SqlServer.ExtensionMethods;
using System.Linq;
using System.Data;
using System.Activities.Statements;

namespace Microsoft.Samples.SqlServer.Activities.Designers
{
  // Interaction logic for QueryDesigner.xaml
  public partial class SqlWhereDesigner
  {
        public SqlConnectionStringBuilder SqlConnectionStringBuilder { get; set; }  

        public SqlWhereDesigner()
        {
            InitializeComponent();
        }

        private string ConnectionString()
        {
            if (this.SqlConnectionStringBuilder != null)
            {
                //Assume Sequence activity with ConnectionBuilderActivity
                ModelItem sequence = this.ModelItem.GetParent(typeof(Sequence));

                //Get ConnectionBuilderActivity. Only uses the first one found
                var connectionBuilderActivity =
                    (from a in sequence.Properties["Activities"].ComputedValue as Collection<System.Activities.Activity>
                     where a.GetType() == typeof(ConnectionBuilderActivity)
                     select a).First() as ConnectionBuilderActivity;

                this.SqlConnectionStringBuilder.DataSource = connectionBuilderActivity.DataSource.Expression.ToString();
                this.SqlConnectionStringBuilder.InitialCatalog = connectionBuilderActivity.InitialCatalog.Expression.ToString();
            }

            return this.SqlConnectionStringBuilder.ToString();
        }

      private void columnNamesComboBox_DropDownOpened(object sender, EventArgs e)
      {
          ComboBox columnNamesComboBox = (sender as ComboBox);

          Mouse.SetCursor(Cursors.Wait);

          using (SqlConnection conn = new SqlConnection(this.ConnectionString()))
          {
              conn.Open();

              //Assume Sequence activity with ConnectionBuilderActivity
              ModelItem sequence = this.ModelItem.GetParent(typeof(Sequence));

              //Get ConnectionBuilderActivity. Only uses the first one found
              var selectDataTableActivity =
                  (from a in sequence.Properties["Activities"].ComputedValue as Collection<System.Activities.Activity>
                   where a.GetType() == typeof(SelectDataTableActivity)
                   select a).First() as SelectDataTableActivity;

              string tableName = selectDataTableActivity.TableSource;

              string[] splitName = tableName.Split(new char[] { '.' });
              string nonSchemaName = splitName.Length > 0 ? splitName[1] : string.Empty;

              List<Column> schema = (from r in conn.GetSchema("Columns").AsEnumerable()
                                     where r.Field<string>("TABLE_NAME") == nonSchemaName
                                     orderby r.Field<int>("ORDINAL_POSITION")
                                     select new Column
                                     {
                                         SchemaName = r.Field<string>("table_schema"),
                                         Name = r.Field<string>("COLUMN_NAME"),
                                         DataType = r.Field<string>("DATA_TYPE"),
                                         DataSize = r.Field<int?>("CHARACTER_MAXIMUM_LENGTH"),
                                         IsNullable = r.Field<string>("IS_NULLABLE") == "YES" ? true : false
                                     }
                                         ).ToList<Column>();

              //NEXT: Data Binding: columnNamesComboBox.ItemsSource
              columnNamesComboBox.Items.Clear();

              foreach (Column c in schema)
              {
                  columnNamesComboBox.Items.Add(string.Format("[{0}]", c.Name));
              }

              Mouse.SetCursor(Cursors.Arrow);
          }
      }

      private void Value_LostFocus(object sender, RoutedEventArgs e)
      {
          this.ModelItem.Properties["Value"].SetValue((sender as TextBox).Text);
      }

  }
}
